/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.vfs;

import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.vfs.MoveRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.type.IResponseMessage;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class MoveCmd extends AbstractCommand<MoveRequestMessage> {

    /**
     * @param req
     */
    public MoveCmd(MoveRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        String fn = req.getBody();
        if (fn.startsWith("$7")) {
            fn = cc.getRealPath(fn);
            try {
                File srcFile = new File(fn);
                if (!srcFile.exists())
                    return new SimpleResponseMessage("e026", FilenameUtils.getName(fn) + " not found.");
                File destFile = new File(req.getDestFile());
                if (destFile.exists())
                    return new SimpleResponseMessage("e026", I18N.getLabel("vfs.exists", FilenameUtils.getName(fn)));
                FileUtils.moveFile(srcFile, destFile);
            } catch (Exception e) {
                return new SimpleResponseMessage("e027", I18N.getLabel("vfs.access.error", e.getMessage()));
            }
        } else {
            File destFile = new File(req.getDestFile());
            if (destFile.exists())
                return new SimpleResponseMessage("e026", I18N.getLabel("vfs.exists", FilenameUtils.getName(fn)));
            File srcFile = new File(req.getBody());
            try {
                FileUtils.moveFile(srcFile, destFile);
            } catch (IOException e) {
                return new SimpleResponseMessage("e027", I18N.getLabel("vfs.access.error", e.getMessage()));
            }
        }
        return new SimpleResponseMessage();
    }

}
